package com.woyao;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.squareup.picasso.Picasso;
import com.woyao.core.FileUtil;
import com.woyao.core.model.GetOrgResponse;
import com.woyao.core.model.KeyValueList;
import com.woyao.core.model.Org;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.FileNotFoundException;
import java.io.IOException;

import retrofit2.Call;

public class OrgActivity extends AppCompatActivity {


    private TextView business;
    private TextView title;
    private TextView description;
    private TextView address;
    private TextView website;
    private ImageView image;
    private ImageView cert;

    private  Button completeBtn;

    boolean changed = false;
    String from = "";

    ProgressDialog progressDialog;
    Org org =   new Org();

    Integer id = 0;

    Integer BUZZ_CODE = 1000;
    Integer TITLE_CODE =  66;
    Integer ADDRESS_CODE =  77;
    Integer WEBSITE_CODE =  88;
    Integer DESC_CODE =  55;
    Integer LOGO_CODE =  100;
    Integer CERT_CODE =  200;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_org_edit);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        Intent intent = getIntent();

        id = intent.getIntExtra( "id",0);
        from = intent.getStringExtra( "from");

        this.setTitle("完善组织信息");

        title = (TextView)findViewById(R.id.orgedit_title);
        description = (TextView)findViewById(R.id.orgedit_desc);
        address = (TextView)findViewById(R.id.orgedit_address);
        website = (TextView)findViewById(R.id.orgedit_website);
        business = (TextView)findViewById(R.id.orgedit_business);
        image = (ImageView) findViewById(R.id.orgedit_image);
        cert = (ImageView) findViewById(R.id.orgedit_cert);
        completeBtn = ( Button) findViewById(R.id.orgedit_finish);


        completeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (business.getText().equals("")) {
                    Common.alert(OrgActivity.this,"请选择组织所在行业");
                    return;
                }

                if (from != null  && from.equals("register") ){
                    Intent intent = new Intent();
                    intent.putExtra("from", from);
                    intent.setClass(OrgActivity.this, FilterHow.class);
                    startActivity(intent);
                }else{
                    Intent intent = new Intent();
                    intent.putExtra("changed", changed );
                    setResult(666, intent);
                    finish();
                }

            }
        });

        title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","orgtitle");
                intent.putExtra("content", org.getTitle());

                intent.setClass(OrgActivity.this,  InputActivity.class);
                startActivityForResult(intent,TITLE_CODE);
            }
        });

        description.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","orgdesc");
                intent.putExtra( "content", org.getDescription() );
                intent.setClass(OrgActivity.this,  InputActivity.class);
                startActivityForResult(intent,DESC_CODE);
            }
        });

        address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","orgaddress");
                intent.putExtra("content", org.getAddress());

                intent.setClass(OrgActivity.this,  InputActivity.class);
                startActivityForResult(intent,ADDRESS_CODE);
            }
        });

        website.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","orgwebsite");
                intent.putExtra("content", org.getWebsite());

                intent.setClass(OrgActivity.this,  InputActivity.class);
                startActivityForResult(intent,WEBSITE_CODE);
            }
        });

        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Open default camera
                checkPerm();
            }
        });

        cert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Open default camera
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/");
                // start the image capture Intent
                startActivityForResult(intent, CERT_CODE);
            }
        });

        business.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("from","org");
                KeyValueList kvl = new KeyValueList();
                kvl.setContent( org.getBusiness() );
                intent.putExtra("business", kvl);
                intent.setClass(OrgActivity.this, FilterBusiness.class);
                startActivityForResult(intent,BUZZ_CODE);
            }
        });


        loadData();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == 520)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {

                //权限被授予
                choosePhoto();

            } else
            {
                // Permission Denied
                Toast.makeText(OrgActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void checkPerm() {
        /**1.在AndroidManifest文件中添加需要的权限。
         *
         * 2.检查权限
         *这里涉及到一个API，ContextCompat.checkSelfPermission，
         * 主要用于检测某个权限是否已经被授予，方法返回值为PackageManager.PERMISSION_DENIED
         * 或者PackageManager.PERMISSION_GRANTED。当返回DENIED就需要进行申请授权了。
         * */
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){ //权限没有被授予

            /**3.申请授权
             * @param
             *  @param activity The target activity.（Activity|Fragment、）
             * @param permissions The requested permissions.（权限字符串数组）
             * @param requestCode Application specific request code to match with a result（int型申请码）
             *    reported to {@link OnRequestPermissionsResultCallback#onRequestPermissionsResult(
             *    int, String[], int[])}.
             * */
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    520);


        }else{//权限被授予
            choosePhoto();

            //直接操作
        }

    }

    void choosePhoto(){

        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/");
        // start the image capture Intent
        startActivityForResult(intent, LOGO_CODE);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed", changed );
        setResult(666, intent);
        finish();
        return true;
    }


    private void loadData(){

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        AsyncTask<Void, Void, GetOrgResponse> needTask = new AsyncTask<Void, Void, GetOrgResponse>() {
            @Override
            protected GetOrgResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetOrgResponse> responseCall= svc.getOrg(WoyaoooApplication.userId,id );
                try {
                    GetOrgResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetOrgResponse response) {
                if(response != null &&response.getContent() !=null){
                    org = response.getContent();
                    
                    renderIt();
                }
                progressDialog.dismiss();
            }
        };
        needTask.execute((Void)null);
    }

//    BusinessSelect select;
    private void renderIt(){

        if (StringUtil.notNullOrEmpty(org.getLogo())) {
            Picasso.with(this)
                    .load(org.getLogo())
                    .into(image);
        } else {
            image.setImageResource(R.drawable.no_avartar);
        }

        title.setText(org.getTitle());
        description.setText(org.getDescription());
        address.setText(org.getAddress());
        website.setText(org.getWebsite());

        if (StringUtil.notNullOrEmpty(org.getCertification())) {
            Picasso.with(this)
                    .load(org.getLogo())
                    .into(image);
        } else {
            image.setImageResource(R.drawable.idcert);
        }

        business.setText( Common.KeyValueToNames( org.getBusiness() )   );

    }

    private void uploadLogo( String picturePath){
        final String filename = FileUtil.getPicObjectKey();
        OSS oss = FileUtil.getOss(getApplicationContext());
        PutObjectRequest put = new PutObjectRequest(FileUtil.bucketName, filename, picturePath);

// 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Common.showSnack(OrgActivity.this, image, "上传成功" );
                Common.setOrgAttr(id,"logo","aliyun"+filename);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常

                }
                Common.showSnack(OrgActivity.this, image, "上传失败" );
            }
        });

    }


    private void uploadCert( String picturePath){
        final String filename = FileUtil.getPicObjectKey();
        OSS oss = FileUtil.getOss(getApplicationContext());
        PutObjectRequest put = new PutObjectRequest(FileUtil.bucketName, filename, picturePath);

// 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Common.showSnack(OrgActivity.this, image, "上传成功" );
                Common.setOrgAttr(id,"certification","aliyun"+filename);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常

                }
                Common.showSnack(OrgActivity.this, image, "上传失败" );
            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == TITLE_CODE && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            org.setTitle(con.toString() );
            title.setText(con);
            Common.setOrgAttr(id,"title", con.toString());
            changed = true;
        }else if(requestCode == ADDRESS_CODE && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            org.setAddress(con.toString() );
            address.setText(con);
            Common.setOrgAttr(id,"address", con.toString());
            changed = true;
        }else if(requestCode == WEBSITE_CODE && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            org.setWebsite(con.toString() );
            website.setText(con);
            Common.setOrgAttr(id,"website", con.toString());
            changed = true;
        }else if(requestCode == DESC_CODE && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            org.setDescription( con.toString());
            changed = true;
            Common.setOrgAttr(id,"description", con.toString());
            description.setText( con.toString());
        }else if(requestCode == BUZZ_CODE && resultCode == 666){
            KeyValueList result = (KeyValueList) data.getExtras().get("result");
            org.setBusiness(result.getContent());
            Common.setOrgAttr( id, "business" , Common.KeyValueToNos( result.getContent()));
            changed = true;
            business.setText(Common.KeyValueToNames( result.getContent()));

        }else if(requestCode == LOGO_CODE &&resultCode==RESULT_OK){
            try {
                Uri selectedImage = data.getData();
                String picturePath;
                Bitmap preview = null;
                try {
                    preview = FileUtil.decodeUri(selectedImage, OrgActivity.this);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(
                        selectedImage, filePathColumn, null, null, null);
                if(cursor!=null) {
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                }
                else
                {
                    picturePath = selectedImage.getPath();
                }

                uploadLogo( picturePath );
                image.setImageBitmap(preview);
                changed  = true;

             }catch(Exception e){
                 e.printStackTrace();
             }
        }else if(requestCode == CERT_CODE &&resultCode==RESULT_OK){
            try {
                Uri selectedImage = data.getData();

                Bitmap preview = null;
                try {
                    preview = FileUtil.decodeUri(selectedImage, OrgActivity.this);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                String picturePath;
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(
                        selectedImage, filePathColumn, null, null, null);
                if(cursor!=null) {
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                }
                else
                {
                    picturePath = selectedImage.getPath();
                }

                uploadCert(picturePath);
                image.setImageBitmap(preview);
                changed  = true;

            }catch(Exception e){
                e.printStackTrace();
            }
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("changed", changed );
            setResult(666, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


}
